package com.zks.handler;

import cn.hutool.core.lang.Singleton;
import cn.hutool.log.Log;
import cn.hutool.log.StaticLog;
import com.zks.Filter.Filter;
import com.zks.action.Action;
import com.zks.setting.Setting;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;

import java.util.Set;

public class ActionHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private static final Log log = StaticLog.get();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {
        final Request request = Request.build(ctx, fullHttpRequest);
        final Response response = Response.build(ctx, request);

        try {

            boolean flag = this.doFilter(request, response);
            if(flag){
                this.doAction(request,response);
            }


        } catch (Exception e) {
            e.printStackTrace();
            Action action=Setting.getAction(Setting.MAPPING_ERROR);
            request.putParam("_e",e);
            action.doAction(request,response);
        }
        //如果发送请求未被触发，则触发之，否则跳过。
        if(false ==response.isSent()){
            response.send();
        }
    }


    /**
     * 执行过滤
     *
     * @return boolean
     * @author zks
     * @date 2019/4/14 12:56
     */
    private boolean doFilter(Request request, Response response) {
        //全局filter
        Filter filter = Setting.getFilter(Setting.MAPPING_ALL);
        if(filter!=null){
            return filter.doFilter(request,response);
        }

        filter = Setting.getFilter(request.getPath());
        if(filter!=null){
            return filter.doFilter(request,response);
        }
        return true;
    }


    private void doAction(Request request,Response response){
        Action action = Setting.getAction(request.getPath());
        if (null == action) {
            //查找匹配所有路径的Action
            action = Setting.getAction(Setting.MAPPING_ALL);
            if(null == action){
                // 非Action方法，调用静态文件读取
/*
                action = Singleton.get(FileAction.class);
*/
            }
        }

        action.doAction(request, response);
    }

}
